package scatter.wwd.rest.componentimpl.recommend;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import scatter.portrait.pojo.user.po.PortraitUser;
import scatter.portrait.rest.user.scheduler.job.AbstractPortraitUserSynchronizeJob;
import scatter.usersimple.pojo.po.UserSimple;
import scatter.usersimple.rest.service.IUserSimpleService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author yangwei
 * @since 2021-09-29 14:13
 */
@Component
public class WwdPortraitUserSynchronizeJob extends AbstractPortraitUserSynchronizeJob {

	/**
	 * 增量用户多少小时以前的算增量，默认24小时
	 */
	@Value("${wwd.recd.user.job.increment.before-hours:24}")
	private Integer incrementUserUpdateTimeBeforeHours;

	@Autowired
	private IUserSimpleService iUserSimpleService;

	@Override
	public List<PortraitUser> fetchAllPortraitUsers(int pageNo, int pageSize) {
		Page page = new Page(pageNo, pageSize);
		Page<UserSimple> result = iUserSimpleService.page(page);
		return result.getRecords().stream().map(this::userSimpleWrap).collect(Collectors.toList());
	}

	@Override
	public List<PortraitUser> fetchIncrementPortraitUsers(int pageNo, int pageSize) {
		Page page = new Page(pageNo, pageSize);
		Page<UserSimple> result = iUserSimpleService.page(page, Wrappers.<UserSimple>lambdaQuery().ge(UserSimple::getUpdateAt, LocalDateTimeUtil.now().minusHours(incrementUserUpdateTimeBeforeHours)));
		return result.getRecords().stream().map(this::userSimpleWrap).collect(Collectors.toList());
	}

	/**
	 * 实体转换
	 * @param userSimple
	 * @return
	 */
	private PortraitUser userSimpleWrap(UserSimple userSimple){
		if (userSimple == null) {
			return null;
		}
		PortraitUser portraitUser = new PortraitUser();
		portraitUser.setUserId(userSimple.getId());
		portraitUser.setGenderDictId(userSimple.getGenderDictId());
		portraitUser.setSourceFromDictId(userSimple.getSourceFromDictId());
		portraitUser.setRegistAt(userSimple.getCreateAt());
		return portraitUser;
	}
}
